/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-07-30
 * Time: 16:12
 */
public class HashBuck2<K, V>{    //泛型版本
    static class Node<K, V>{  //哈希桶的每个元素是一个单链表
        public K key;
        public V val; //val这里我们默认全部设置999, 这次模拟不需要val
        public Node<K, V> next;
        public Node(K key, V val){
            this.key = key;
            this.val = val;
        }
    }
    public static final double LOAD_FACTOR = 0.75;  //负载因子的上限
    public Node<K, V>[] array;    //哈希数组
    public int usedSize;

    public HashBuck2(){
        array = (Node<K, V>[]) new Node[10];
    }
    public void push(K key, V val){
        int hash =  key.hashCode(); //获取哈希码
        int index = hash % array.length; //除留余数法(哈希函数)找到哈希的位置
        //看一下key是不是在当前位置存储过，如果存储过更新最新的key(map的key不能有重复值)
        Node<K, V> cur = array[index];
        while(cur != null){     //遍历单链表
           if(cur.key.equals(key)){
               cur.key = key;
               return;
           }
           cur = cur.next;
        }
        //走到这里说明是新元素
        //头插插入新元素
        Node<K, V> node = new Node<K, V>(key, val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
    }

    public V get(K key){
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while(cur != null){
            if(cur.key.equals(key)){
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
